﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Haidou.Wpf.Util
{
	public static class JSON
	{

		public static T Parse<T>(string json) where T : class
		{
			try
			{


				return string.IsNullOrEmpty(json) ? null : JsonConvert.DeserializeObject<T>(json);
				{
				}

			}
			catch (Exception ex)
			{
				Debug.WriteLine(ex.Message);
				return null;
			}

		}

		public static string ToJSON(object data)
		{
			return JsonConvert.SerializeObject(data);
		}

		public static JToken GetValueByPath(this JToken data, string path)
		{
			try
			{
				string[] paths = path.Split('.'); ;
				int index = 0;
				foreach (string item in paths)
				{
					data = int.TryParse(item, out index) ? (data as JArray)[index] : data[item];
				}
			}
			catch (Exception)
			{
				return null;
			}
			return data;
		}

		public static void SetValueByPath(this JToken data, string path, JToken v)
		{
			try
			{
				string[] paths = path.Split('.'); ;
				int index = 0;
				int i = 0;
				int len = paths.Length;
				foreach (string item in paths)
				{
					i++;

					if (i == len)
					{
						data[item] = v;
						return;
					}

					data = int.TryParse(item, out index) ? (data as JArray)[index] : data[item];
				}
			}
			catch (Exception)
			{

			}
		}

		/// <summary>
		/// 将数据复制到指定的对象
		/// </summary>
		/// <param name="data"></param>
		/// <param name="tag"></param>
		public static void CopyTo(this JObject data, JObject tag)
		{
			foreach (KeyValuePair<string, JToken?> item in data)
			{
				string key = item.Key;
				JObject? temp = item.Value as JObject;
				if (temp != null)
				{
					if (tag.ContainsKey(key) && tag[key] is JObject)
					{
						CopyTo(temp, tag[key] as JObject);
					}
					else
					{
						tag[key] = temp;
					}
				}
				else
				{
					tag[key] = item.Value;
				}
			}
		}

		/// <summary>
		/// 从source中获取自己属性的值
		/// </summary>
		/// <param name="data"></param>
		/// <param name="source"></param>
		public static void CopyByObj(this JObject data, JObject source)
		{
			foreach (KeyValuePair<string, JToken?> item in data)
			{
				if (source.ContainsKey(item.Key))
				{
					data[item.Key] = source[item.Key];
				}
			}

		}

		//public static string ToQueryString(this IEnumerable<KeyValuePair<string, string>> pairs)
		//{
		//    return string.Join("&", pairs.Select(p => p.Key + "=" + HttpUtility.UrlEncode(p.Value)));
		//}
	}
}
